package com.zs.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zs.blog.converter.MenuConverter;
import com.zs.blog.dao.IMenuMapper;
import com.zs.blog.model.entity.Menu;
import com.zs.blog.model.vo.MenuLabelListVO;
import com.zs.blog.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Title: IMenuServiceImpl
 * @Author zs
 * @Package com.zs.blog.service.impl
 * @Date 2025/8/25 22:41
 * @description: 菜单服务层实现类
 */
@Service
public class IMenuServiceImpl extends ServiceImpl<IMenuMapper, Menu> implements IMenuService {

    public IMenuMapper menuMapper;

    @Autowired
    public IMenuServiceImpl(IMenuMapper menuMapper){
        this.menuMapper = menuMapper;
    }


    /**
     * 获取菜单层级信息列表
     *
     * @return 菜单层级信息列表
     */
    @Override
    public List<MenuLabelListVO> listMenuLevelInfo() {
        // 查询所有菜单信息
        LambdaQueryWrapper<Menu> lqw = new LambdaQueryWrapper<>();
        List<Menu> allMenu = menuMapper.selectList(lqw);

        // 数据映射
        List<MenuLabelListVO> menuLabelListVOS = MenuConverter.INSTANCE.menuList2MenuLabelListVO(allMenu);

        // 构建菜单层级树 一级-->二级-->三级
        // 顶级
        List<MenuLabelListVO> topMenuLevel = new ArrayList<>();
        menuLabelListVOS.forEach(item->{
            if (item.getParentId() == 0){
                topMenuLevel.add(item);
            }
        });
        // 子集，2 3级  父级X有Y个子
        Map<Long, List<MenuLabelListVO>> subMenuLevel = menuLabelListVOS.stream()
                .filter(item -> item.getParentId() != 0)
                .collect(Collectors.groupingBy(MenuLabelListVO::getParentId));

        // 设置层级关系 父找子
        for(MenuLabelListVO menuLabelListVO:menuLabelListVOS){
            // 寻找当前菜单的子集并设置
            List<MenuLabelListVO> menuLabelList = subMenuLevel.get(menuLabelListVO.getId());
            // 顶级可能没有子集、最后一级没有子集
            if(menuLabelList != null){
                menuLabelListVO.setChildren(menuLabelList);
            }
        }
        System.out.println("111111");
        return topMenuLevel;
    }


}
